package edu.nwpu.utils;


import org.apache.commons.lang.RandomStringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public abstract class ImageUtil {

    private static final int RANDOM_LENGTH = 10;

    private static final Set<String> TYPE_SET = new HashSet<String>() {
        {
            add("png");
            add("jpg");
        }
    };

    public static boolean checkFileType(MultipartFile file) {
        try {
            String name = file.getOriginalFilename();
            String type = name.substring(name.lastIndexOf(".")+1);
            return TYPE_SET.contains(type);
        } catch (Exception e) {
            return false;
        }
    }

    public static String generateFileName(MultipartFile file) {
        String str = "" + new Date().getTime();
        str += RandomStringUtils.randomAlphanumeric(RANDOM_LENGTH);
        String name = file.getOriginalFilename();
        str += name.substring(name.lastIndexOf("."));
        return str;
    }
}
